#include "acceptor.hpp"
#include "logger.h"
namespace moqi
{
Acceptor::Acceptor(const unsigned int& port, const string& ip)
:_addr(port, ip),
_sock()
{

}

Acceptor::~Acceptor()
{

}

void Acceptor::ready()
{
    setResuzeAddr(true);
    setResuzePort(true);
    bind();
    listen();
    LOG_INFO("Acceptor all ready");
}

int Acceptor::accept()
{
   int ret = ::accept(_sock.fd(), nullptr, nullptr);
   if(ret < 0)
   {
       LOG_ERROR("accept");
   }
   return ret;

}

int Acceptor::getSockFd()
{
    return _sock.fd();
}

void Acceptor::setResuzeAddr(bool on)
{
    int one  = on? 1 : 0;
    int ret = setsockopt(_sock.fd(), SOL_SOCKET,SO_REUSEADDR, &one, sizeof(one));
    if(ret < 0)
    {
        LOG_ERROR("setsockopt addr");
    }
}

void Acceptor::setResuzePort(bool on)
{
    int one  = on? 1 : 0;
    int ret = setsockopt(_sock.fd(), SOL_SOCKET,SO_REUSEPORT, &one, sizeof(one));
    if(ret < 0)
    {
        LOG_ERROR("setsockopt port");
    }
}

void Acceptor::bind()
{ //此处注意，需要用匿名命名空间，表示这个bind是系统库的bind，而不是自己定义的这个
    int ret = ::bind(_sock.fd(), (const struct sockaddr*)_addr.getInetAddress(), sizeof(_addr));
    if(ret < 0)
    {
        LOG_ERROR("bind");
    }
    LOG_INFO("Acceptor bind");
}

void Acceptor::listen()
{//此处注意，需要用匿名命名空间，表示这个listen是系统库的listen，而不是自己定义的这个
    int ret = ::listen(_sock.fd(), 20000);
    if(ret < 0)
    {
        LOG_ERROR("listen");
    }
    LOG_INFO("Acceptor listen");
}

}//end of namespace moqi


